package ch.rheintalconnection.sysventory.technicalServices.wmi;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import ch.rheintalconnection.sysventory.dto.ProgramDto;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

public class ProgramScan {
	
	private ActiveXComponent axWMI;
	private String host;
	
	public static final String QUERY = "SELECT * FROM Win32_Product";
	
	private static Logger logger = LogManager.getLogger(ProgramScan.class);

	public ProgramScan(ActiveXComponent axWMI, String host) {
		super();
		this.axWMI = axWMI;
		this.host = host;
	}

	public List<ProgramDto> scan(){
		
		ArrayList<ProgramDto> programs = new ArrayList<ProgramDto>();
		
		Variant vCollection = axWMI.invoke("ExecQuery", new Variant(QUERY));
		EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
		Dispatch item = null;
		
		ProgramDto programDto;
		while (enumVariant.hasMoreElements()) {
			item = enumVariant.nextElement().toDispatch();
		
			String description = Dispatch.call(item, "Caption").toString();
			String version = Dispatch.call(item, "Version").toString();     
            
			programDto = new ProgramDto(description, version);
			programs.add(programDto);
			
			logger.debug(host + " scanned " + programDto);
		}
		return programs;		
	}
	
}
